2
2
.
.
1
1
1
1
.
.
1
1
2
2
F
F
r
r
o
o
m
m
J
J
S
S
O
O
N
N
A
A
r
r
r
r
a
a
y
y
I
I
n
n
f
f
o
o
[
[
G
G
]
]
This tutorial shows how to use @RequestBody Annotation to convert JSON Array from HTTP Request into List of Objects.
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables @Controller, @RequestMapping and Tomcat Server
MyController
Person
POSTMAN
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: springboot_httprequest_requestbody_json_array (add Spring Boot Starters from the table)
Create Package: controllers (inside main package)
– Create Class: MyController.java (inside package controllers)
Create Package: entities (inside main package)
– Create Class: Person.java (inside package controllers)
Person.java
package com.ivoronline.springboot_httprequest_requestbody_json_array.entities;
public class Person {
public String name;
public Integer age;
}
MyController.java
package com.ivoronline.springboot_httprequest_requestbody_json_array.controllers;
import com.ivoronline.springboot_httprequest_requestbody_json_array.entities.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
public class MyController {
@ResponseBody
@RequestMapping("/AddPersons")
public String addPersons(@RequestBody List<Person> persons) {
//ITERATE THROUGH LIST
String result = "";
for (Person person : persons) {
String name = person.name;
Integer age = person.age;
result += name + " is " + age + " years old \n";
}
//RETURN SOMETHING
return result;
}
}
R
R
e
e
s
s
u
u
l
l
t
t
s
s
Start Postman
POST: http://localhost:8080/AddPersons
Headers: (copy from below)
Body: (copy from below)
Send
Headers (add Key-Value)
Content-Type: application/json
Body (option: raw)
[
{
"name" : "Jack",
"age" : "20"
},
{
"name" : "Bill",
"age" : "50"
}
]
POST http://localhost:8080/AddPersons
HTTP Response Body
Jack is 20 years old
Bill is 50 years old
Application Structure
pomx.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>